package department.fc.service;

import java.sql.SQLException;
import java.util.ArrayList;

import department.fc.dao.DepartmentDAO;
import department.fc.domain.Department;
import department.fc.exception.DuplicatedIDException;
import department.fc.exception.RecordNotFoundException;

public class DepartmentService {

	private DepartmentDAO dao;
	private static DepartmentService instance = new DepartmentService();
	
	private DepartmentService(){
		dao = DepartmentDAO.getInstance();
	}
	
	public static DepartmentService getInstance(){
		return instance;
	}
	/**
	 * 부서 등록 메소드
	 * @param department
	 * @throws SQLException
	 * @throws DuplicatedIDException 
	 */
	public void registerDepartment(Department department) throws SQLException, DuplicatedIDException{
//		1. 부서아이디가 등록된 아이디인지 체크
		Department d = dao.selectDepartmentById(department.getDepartmentId());
//		1-1 등록되지 않은 아이디면 - 부서 테이블에 insert
		if(d == null){
			dao.insertDepartment(department);
		}else{
//		1-2 등록된 아이디면 - DuplicatedIDException 예외 발생
			throw new DuplicatedIDException(department.getDepartmentId()+"는 등록된 아이디입니다.");
		}
	}
	/**
	 * 부서 아이디로 부서 삭제 메소드
	 * @param departmentId
	 * @throws SQLException
	 * @throws RecordNotFoundException 
	 */
	public void removeDepartmentById(String departmentId) throws SQLException, RecordNotFoundException{
//		1. 삭제할 부서가 있는지 조회
		Department dept = dao.selectDepartmentById(departmentId);
		if(dept == null){
//		1-1 : 없으면 - 예외발생(RecordNotFoundException)
			throw new RecordNotFoundException(departmentId+"는 없는 아이디입니다.");
		}
//		1-2 : 있으면 - 삭제처리
		dao.deleteDepartmentById(departmentId);
	}
	/**
	 * 부서 수정 메소드
	 * @param department
	 * @throws SQLException
	 * @throws RecordNotFoundException 
	 */
	public void modifyDepartment(Department department) throws SQLException, RecordNotFoundException{
//		1. 수정할 부서가 있는지 조회
		String departmentId = department.getDepartmentId();
		Department dept = dao.selectDepartmentById(departmentId);
		if(dept == null){
//		1-1 : 없으면 - 예외발생(RecordNotFoundException)
			throw new RecordNotFoundException(departmentId+"는 없는 아이디입니다.");
		}
//		1-2 : 있으면 - 수정처리
		dao.updateDepartmentById(department);
	}
	/**
	 * 부서 아이디로 부서정보 조회 메소드
	 * @param departmentId
	 * @return
	 * @throws SQLException
	 */
	public Department getDepartmentById(String departmentId) throws SQLException{
		return dao.selectDepartmentById(departmentId);
	}
	/**
	 * 부서 목록 조회 메소드
	 * @return
	 * @throws SQLException
	 */
	public ArrayList<Department> getDepartmentList() throws SQLException{
		return dao.selectDepartmentList();
	}
	public ArrayList<Department> searchDepartmentByLocation(String location) throws SQLException{
		return dao.selectDepartementsByLocation(location);
	}
	
}

























